const getColums = array => {
  var columns = [];
  const each = data => {
    data.forEach(item => {
      var o = { label: item.label, prop: item.prop };
      if (item.children) {
        delete o.prop;
        o.children = getColums(item.children);
      }
      columns.push(o);
    });
  };
  each(array);
  return columns;
};

const getChildren = array => {
  var columns = [];
  const each = data => {
    data.forEach(item => {
      var o = { label: item.label, prop: item.prop };
      if (item.children) {
        each(item.children);
      } else {
        columns.push(o);
      }
    });
  };
  each(array);
  return columns;
};

const handle = item => {
  if (item === undefined || item === null || item === '') {
    return '--';
  } else {
    return item;
  }
};

export const exportDataHandle = (col, rows) => {
  const columns = getColums(col);

  const children = getChildren(columns);

  const o = v => {
    return children.reduce((item, next) => {
      item[next[`prop`]] = handle(v[next[`prop`]]);
      return item;
    }, {});
  };

  const data = rows.map(item => o(item)); // 获取数据

  return {
    columns,
    data
  };
};

// 拼接报表
export const tableHandle = t => {
  var tr = t[1].getElementsByTagName('tbody')[0].innerHTML;
  for (let i = 2; i < t.length; i++) {
    const trs = t[i].getElementsByTagName('tbody')[0].getElementsByTagName('tr');
    for (let j = 0; j < trs.length; j++) {
      const tds = trs[j].getElementsByTagName('td');
      for (let k = 0; k < tds.length; k++) {
        if (tds[k].getAttribute('colspan') === '2') {
          tds[k].setAttribute('colspan', 1);
        }
      }
    }
    const tbody = t[i].getElementsByTagName('tbody')[0];
    tbody.removeChild(tbody.childNodes[0]);
    tr += tbody.innerHTML;
  }
  t[0].getElementsByTagName('tbody')[0].innerHTML = tr; // 拼接赋值

  const img = t[0].getElementsByTagName('img');
  const span = t[0].getElementsByTagName('span');
  for (let i = 0, l = img.length; i < l; i++) {
    var src = img[i].getAttribute('src');
    var index = src.indexOf('/api');
    img[i].setAttribute('src', src.substring(index));
  }
  for (let i = 0, l = span.length; i < l; i++) {
    const style = span[i].getAttribute('style');
    span[i].setAttribute(
      'style',
      style + ' font-size:15px !important;'
    );
  }
};
